#!/usr/local/bin/python
# -*- coding: utf-8 -*-
from datetime import datetime

from sqlalchemy import Column, Integer, Date, Float, and_, Text
from sqlalchemy.orm import declarative_base

import init
from init import session
from initLogger import logger
from toolkit import fromVoucherPathToName

Base = declarative_base()

class AnnualYieldAlchemy(Base):
    '''
    类功能：记录年化收益率
    '''

    __tablename__ = "annual_yield"

    id = Column(Integer, primary_key=True, autoincrement=True, comment="")
    observe_date = Column(Date, comment="观察年化收益率的日期")
    year = Column(Integer, comment="时间年份")
    month = Column(Integer, comment="时间月份")
    investment_path = Column(Text, comment="投资途径")
    investment_name = Column(Text, comment="投资名称")  #为后期投资途径相同的不同投资，用这个字段做区分。



    saved_total_money_value = Column(Float, comment="投资的原始本金的总和")
    drawed_total_money_value = Column(Float, comment="投资过程中提现的金额总和")
    dividend_total_value = Column(Float, comment="投资过程中获得的分红金额的总和")
    current_real_total_value = Column(Float, comment="当前产品的实际总金额")

    #current_principal_total_value =  self.saved_total_money_value - self.drawed_total_money_value - self.dividend_total_value
    current_principal_total_value = Column(Float, comment="当前剩余本金总和，截止当前除去提取、分红后，实际存入的金额总和")
    earnings_total_value = Column(Float, comment="当前收益总金额")

    xirr_value = Column(Float, comment="年化收益率")
    # total_yield_rate_value =  (self.current_real_total_value - self.current_principal_total_value)/self.current_real_total_value
    total_yield_rate_value = Column(Float, comment="总收益率")  # 还没想好怎么算

    def __init__(self,
                 observeDate=None,
                 investmentName="",
                 savedTotalMoneyValue=0.0,
                 drawedTotalMoneyValue=0.0,
                 dividendTotalValue=0.0,
                 currentRealTotalValue=0.0,
                 xirrValue=0.0
                 ):
        '''
        函数功能：初始化函数
        :param observeDate:
        :param investmentPath:
        :param savedTotalMoneyValue:
        :param drawedTotalMoneyValue:
        :param dividendTotalValue:
        :param currentRealTotalValue:
        :param xirrValue:
        '''


        self.observe_date = observeDate
        if observeDate!=None:
            self.year = observeDate.year
            self.month = observeDate.month
            self.investment_path = "investmentPath"
            #self.investment_name = fromVoucherPathToName(self.investment_path)
            self.investment_name = investmentName
            self.saved_total_money_value = savedTotalMoneyValue
            self.drawed_total_money_value = drawedTotalMoneyValue
            self.dividend_total_value = dividendTotalValue
            self.current_real_total_value = currentRealTotalValue

            self.current_principal_total_value = self.saved_total_money_value - self.drawed_total_money_value - self.dividend_total_value
            self.earnings_total_value = self.current_real_total_value - self.current_principal_total_value

            self.xirr_value = xirrValue
            self.total_yield_rate_value = (self.current_real_total_value - self.current_principal_total_value)/self.current_principal_total_value


            self.showDate()



    def AddInvestmentItem(self):
        '''
        函数功能；添加一条投资流水记录
        :return:
        '''
        session.add(self)
        session.commit()


    def SearchInvestmentByMonth(self, year, month):
        '''
        函数功能：查询指点月份各产品的投资收益率xirr
        :param year:
        :param month:
        :return:
        '''

        annualYieldInfo = session.query(AnnualYieldAlchemy).filter(and_(AnnualYieldAlchemy.year == year,  \
                                                                        AnnualYieldAlchemy.month == month)) \
                                                           .all()

        return annualYieldInfo
    def SearchInvestmentFlow(self, investmentName, year):
        '''
        函数功能：查询指定投资品种的投资流水记录。
        :param investmentName:
        :param flowType:
        :return:
        '''

        annualYieldInfo = session.query(AnnualYieldAlchemy).filter(and_(AnnualYieldAlchemy.investment_name == investmentName,
                                                                              AnnualYieldAlchemy.year == year)) \
                                                                 .all()

        return  annualYieldInfo





    def showDate(self):
        '''
        函数功能：对数据进行展示
        :return:
        '''
        logger.debug("时间:%s" % (self.observe_date.strftime("%Y-%m-%d")))
        logger.debug("名称:%s" % (self.investment_name))
        logger.debug("存入总金额:%.2f" % (self.saved_total_money_value))
        logger.debug("提取总金额:%.2f" % (self.drawed_total_money_value))
        logger.debug("分红总金额:%.2f" % (self.dividend_total_value))

        logger.debug("实际总金额:%.2f" % (self.current_real_total_value))  #现存总金额
        logger.debug("实际本金总额:%.2f" % (self.current_principal_total_value))  #现存本金总额
        logger.debug("实际收益总额:%.2f" % (self.earnings_total_value))  # 现存本金总额
        logger.debug("年化收益率：{:.2%}".format(self.xirr_value))
        logger.debug("总收益率：{:.2%}".format(self.total_yield_rate_value))



def main():

    annualYieldAlchemy = AnnualYieldAlchemy(observeDate=datetime.now(),
                                            investmentPath="资产->投资->理财->沪深300指数基金",
                                            savedTotalMoneyValue=100.0,
                                            drawedTotalMoneyValue=20.0,
                                            dividendTotalValue=30.0,
                                            currentRealTotalValue=80.0,
                                            xirrValue=0.08)
    annualYieldAlchemy.AddInvestmentItem()

AnnualYieldAlchemy.metadata.create_all(init.engine)
if __name__ == '__main__':
    main()